package me.zhengjie.gas.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import me.zhengjie.gas.dto.DtuGpsLogDto;
import me.zhengjie.gas.repositories.DtuGpsLogRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class DtuGpsLogService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private DtuGpsLogRepository dtuGpsLogRepository;

	public String requestAddress(double lat, double lon) {
		String sql = "select key_value from eladmin.app_key where key_name='天地图'";
		String key = jdbcTemplate.queryForObject(sql, String.class);
		if (StringUtils.isEmpty(key)) {
			return "No found key";
		}

		try {
			String postStr = "{'lon':" + lon + ",'lat':" + lat + ",'ver':1}";
			postStr = URLEncoder.encode(postStr, StandardCharsets.UTF_8);
			String url = "http://api.tianditu.gov.cn/geocoder?postStr=" + postStr + "&type=geocode&tk=" + key;
			// 发送http请求
			ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);

			String content = response.getBody();  //restTemplate.getForObject(url, String.class);
			ObjectMapper objectMapper = new ObjectMapper();

			Map map = objectMapper.readValue(content, Map.class);
			String status = (String) map.get("status");
			if (!"0".equals(status)) {
				return null;
			}

			Map result = (Map) map.get("result");
			if (result != null) {
				String address = (String) result.get("formatted_address");
				return address;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public void onRecveive(String deviceId, Map map) {
		String sql = "select id from eladmin.dtu_device where device_mac='" + deviceId + "' and is_active";
		Integer id = jdbcTemplate.queryForObject(sql, Integer.class);
		if (id == null) {
			return;
		}

		try {
			DtuGpsLogDto logDto = new DtuGpsLogDto();
			logDto.setDeviceId(id);
			logDto.setMac(deviceId);
			logDto.setImei(map.get("IMEI").toString());
			if (map.get("gps") != null) {
				List<Double> gps = (List<Double>) map.get("gps");
				logDto.setLat(gps.get(1));
				logDto.setLon(gps.get(0));
			}

			if (map.get("gsmloc") != null) {
				List<Double> gps = (List<Double>) map.get("gsmloc");
				logDto.setGsmLat(gps.get(1));
				logDto.setGsmLon(gps.get(0));
			}

			if (map.get("gsminfo") != null) {
				List<Integer> gps = (List<Integer>) map.get("gsminfo");
				logDto.setGsmInfo0(gps.get(0));
				logDto.setGsmInfo1(gps.get(1));
				logDto.setGsmInfo2(gps.get(2));
				logDto.setGsmInfo3(gps.get(3));
			}

			// 查询地址
//			String address = requestAddress(logDto.getLat(), logDto.getLon());
//			if (address != null) {
//				logDto.setAddress(address);
//			}

			if (map.get("time") != null) {
				String timeStr = (String) map.get("time");
				LocalDateTime time = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
				logDto.setCreatedTs(time);
			} else {
				logDto.setCreatedTs(LocalDateTime.now());
			}
			dtuGpsLogRepository.save(logDto);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
